<template>
  <ControlWrap
    :custom-style="{
      backgroundImage: 'linear-gradient(to bottom right, #f9fafb , #eff6ff)',
    }"
  >
    <!-- 主要内容区 -->
    <main class="pt-24 pb-8 px-4 max-w-7xl mx-auto">
      <!-- 数据概览卡片 -->
      <div class="grid grid-cols-4 gap-6 mb-8">
        <div
          v-for="(stat, index) in statistics"
          :key="index"
          class="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow duration-300"
        >
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-500 mb-2">{{ stat.label }}</p>
              <h3 class="text-2xl font-semibold">{{ stat.value }}</h3>
            </div>
            <div
              :class="`w-12 h-12 rounded-full flex items-center justify-center ${stat.iconBg}`"
            >
              <i :class="`${stat.icon} text-white text-xl`"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center">
            <span
              :class="`${
                stat.trend === 'up' ? 'text-green-500' : 'text-red-500'
              }`"
            >
              <i :class="`fas fa-arrow-${stat.trend} mr-1`"></i>
              {{ stat.percentage }}%
            </span>
            <span class="text-gray-500 ml-2" @click="toto">较上周</span>
          </div>
        </div>
      </div>
      <!-- 图表区域 -->
      <div class="grid grid-cols-2 gap-6 mb-8">
        <div class="bg-white rounded-lg p-6 shadow-sm">
          <h3 class="text-lg font-semibold mb-4">访问趋势</h3>
          <div ref="visitChart" class="w-full h-80"></div>
        </div>
        <div class="bg-white rounded-lg p-6 shadow-sm">
          <h3 class="text-lg font-semibold mb-4">用户分布</h3>
          <div ref="userChart" class="w-full h-80"></div>
        </div>
      </div>
      <!-- 最新动态 -->
      <div class="grid grid-cols-3 gap-6">
        <div class="bg-white rounded-lg p-6 shadow-sm col-span-2">
          <h3 class="text-lg font-semibold mb-4">最新文章</h3>
          <div
            class="space-y-4 h-[600px] overflow-y-auto"
            ref="articleList"
            @scroll="handleScroll"
          >
            <div
              v-for="(article, index) in displayArticles"
              :key="index"
              class="flex items-start p-4 hover:bg-gray-50 rounded-lg transition-colors duration-200"
            >
              <img
                :src="article.cover"
                class="w-20 h-20 rounded-lg object-cover"
                :alt="article.title"
              />
              <div class="ml-4 flex-1">
                <h4 class="font-medium mb-2">{{ article.title }}</h4>
                <p class="text-gray-500 text-sm mb-2">{{ article.excerpt }}</p>
                <div class="flex items-center text-sm text-gray-400">
                  <span>{{ article.date }}</span>
                  <span class="mx-2">·</span>
                  <span>{{ article.views }} 阅读</span>
                </div>
              </div>
            </div>
            <div v-if="loading" class="flex justify-center items-center py-4">
              <i class="fas fa-spinner fa-spin text-blue-500"></i>
              <span class="ml-2 text-gray-500">加载中...</span>
            </div>
            <div v-if="noMoreData" class="text-center py-4 text-gray-500">
              已经到底了
            </div>
          </div>
        </div>
        <div class="bg-white rounded-lg p-6 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold">今日行程</h3>
            <div class="relative">
              <button
                @click="showDatePicker = !showDatePicker"
                class="flex items-center space-x-2 px-3 py-1.5 bg-white border border-gray-200 rounded-lg hover:border-blue-400 transition-colors duration-200"
              >
                <span class="text-sm text-gray-600">{{
                  formatDate(selectedDate)
                }}</span>
                <i class="fas fa-calendar-alt text-gray-400"></i>
              </button>
              <div
                v-if="showDatePicker"
                class="calendar absolute right-0 top-12 w-80 bg-white rounded-lg shadow-xl border border-gray-100 p-4 z-50"
              >
                <div class="flex items-center justify-between mb-4">
                  <button
                    @click="prevMonth"
                    class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                  >
                    <i class="fas fa-chevron-left text-gray-500"></i>
                  </button>
                  <span class="font-medium">{{ currentMonthYear }}</span>
                  <button
                    @click="nextMonth"
                    class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                  >
                    <i class="fas fa-chevron-right text-gray-500"></i>
                  </button>
                </div>
                <div class="grid grid-cols-7 gap-1 mb-2">
                  <div
                    v-for="day in ['日', '一', '二', '三', '四', '五', '六']"
                    :key="day"
                    class="text-center text-sm text-gray-500 py-1"
                  >
                    {{ day }}
                  </div>
                </div>
                <div class="grid grid-cols-7 gap-1">
                  <button
                    v-for="day in calendarDays"
                    :key="day.date"
                    @click="selectDate(day)"
                    :class="[
                      'p-2 rounded-lg text-sm transition-colors hover:bg-blue-50',
                      {
                        'text-gray-400': !day.isCurrentMonth,
                        'bg-blue-500 text-white hover:bg-blue-600':
                          isSelectedDate(day),
                        'text-gray-700':
                          day.isCurrentMonth && !isSelectedDate(day),
                      },
                    ]"
                  >
                    {{ new Date(day.date).getDate() }}
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="space-y-4">
            <div
              v-for="(schedule, index) in schedules"
              :key="index"
              class="flex items-start p-4 hover:bg-gray-50 rounded-lg transition-colors duration-200 border-l-4"
              :class="schedule.statusColor"
            >
              <div class="mr-4">
                <p class="text-sm font-medium text-gray-600">
                  {{ schedule.time }}
                </p>
                <p class="text-xs text-gray-400">{{ schedule.duration }}</p>
              </div>
              <div class="flex-1">
                <p class="font-medium text-gray-800 mb-1">
                  {{ schedule.title }}
                </p>
                <div class="flex items-center text-sm text-gray-500">
                  <i class="fas fa-map-marker-alt mr-1"></i>
                  <span>{{ schedule.location }}</span>
                </div>
                <div class="flex items-center mt-2 space-x-2">
                  <div
                    v-for="(attendee, idx) in schedule.attendees"
                    :key="idx"
                    class="w-6 h-6 rounded-full overflow-hidden border-2 border-white -ml-2 first:ml-0"
                  >
                    <img
                      :src="attendee.avatar"
                      :alt="attendee.name"
                      class="w-full h-full object-cover"
                    />
                  </div>
                  <span class="text-xs text-gray-500"
                    >+{{ schedule.totalAttendees }}</span
                  >
                </div>
              </div>
              <div class="ml-4">
                <button class="text-gray-400 hover:text-blue-600">
                  <i class="fas fa-ellipsis-v"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div></main
  ></ControlWrap>
</template>
<script setup>
import * as echarts from "echarts";
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const toto = () => {
  router.push({
    // name: "UserList",
    // name:"ArticleManagement",
    name: "MeunManagement",
    // name:"RoleManagement"
  });
};
// 响应式状态
const loading = ref(false);
const noMoreData = ref(false);
const page = ref(1);
const showDatePicker = ref(false);
const selectedDate = ref(new Date());
const currentMonth = ref(new Date());
const visitChart = ref(null);
const userChart = ref(null);
const articleList = ref(null);

const avatarUrl = ref(
  "https://ai-public.mastergo.com/ai/img_res/bba37e05f4a0ab827022eff442074afb.jpg"
);
const displayArticles = ref([]);

const statistics = ref([
  {
    label: "总访问量",
    value: "234,567",
    icon: "fas fa-eye",
    iconBg: "bg-blue-500",
    trend: "up",
    percentage: 12,
  },
  {
    label: "文章数",
    value: "1,234",
    icon: "fas fa-file-alt",
    iconBg: "bg-green-500",
    trend: "up",
    percentage: 8,
  },
  {
    label: "活跃用户",
    value: "45,678",
    icon: "fas fa-users",
    iconBg: "bg-purple-500",
    trend: "up",
    percentage: 15,
  },
  {
    label: "评论数",
    value: "12,345",
    icon: "fas fa-comments",
    iconBg: "bg-orange-500",
    trend: "down",
    percentage: 3,
  },
]);

const allArticles = ref([
  {
    title: "人工智能在现代企业中的应用与发展趋势",
    excerpt:
      "探讨人工智能技术如何改变传统企业的运营模式，以及未来可能带来的影响和机遇...",
    date: "2024-01-15",
    views: 1234,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/97c583067abcd1973e321a54c4c92b34.jpg",
  },
  {
    title: "可持续发展：企业社会责任的新思考",
    excerpt:
      "深入分析企业在环境保护、社会公益等方面的责任，探讨可持续发展战略...",
    date: "2024-01-14",
    views: 956,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/e9ced8dedb508bda840fcf87af4203ac.jpg",
  },
  {
    title: "数字化转型：传统企业的机遇与挑战",
    excerpt: "分析数字化转型过程中企业面临的主要问题，并提供可行的解决方案...",
    date: "2024-01-13",
    views: 845,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/52607f607d75eb80d3c96ba0d6e061da.jpg",
  },
  {
    title: "5G技术对未来商业模式的影响",
    excerpt: "深度解析5G技术将如何重塑商业生态，带来新的商业机会与挑战...",
    date: "2024-01-12",
    views: 732,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/2c7ee806d31c8de8e1d71b1b93dce025.jpg",
  },
  {
    title: "区块链技术在供应链管理中的应用",
    excerpt: "探讨区块链如何提升供应链的透明度和效率，实现全程可追溯...",
    date: "2024-01-11",
    views: 689,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/e94ccf75425ce8e07b9e5199ef1ac284.jpg",
  },
  {
    title: "远程办公新常态下的团队管理",
    excerpt: "分享远程办公环境下提升团队协作效率和员工积极性的实用策略...",
    date: "2024-01-10",
    views: 567,
    cover:
      "https://ai-public.mastergo.com/ai/img_res/350b7f93573ab7b1a4f0d3237ed5ef25.jpg",
  },
]);

const schedules = ref([
  {
    time: "09:00",
    duration: "1小时",
    title: "产品设计评审会议",
    location: "六楼会议室A",
    statusColor: "border-blue-500",
    attendees: [
      {
        name: "张晓华",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/56e16970b78bd17757c99239e596c3bb.jpg",
      },
      {
        name: "李明",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/88733104d1a568272a948a048b5c15bc.jpg",
      },
    ],
    totalAttendees: 5,
  },
  {
    time: "11:00",
    duration: "45分钟",
    title: "客户需求沟通",
    location: "线上会议",
    statusColor: "border-green-500",
    attendees: [
      {
        name: "王思琪",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/70519c396dc0a494c33d5bfc602bdac7.jpg",
      },
      {
        name: "赵志强",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/294a45d65bc45a77fbc818aa119ab3fc.jpg",
      },
    ],
    totalAttendees: 4,
  },
  {
    time: "14:30",
    duration: "2小时",
    title: "季度战略规划会",
    location: "八楼大会议室",
    statusColor: "border-purple-500",
    attendees: [
      {
        name: "陈总",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/61854be37fa32a1048a5eda7cd5402f8.jpg",
      },
      {
        name: "林经理",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/73e7a4e99cde36b0b4065b279f663949.jpg",
      },
    ],
    totalAttendees: 8,
  },
  {
    time: "16:30",
    duration: "1小时",
    title: "技术团队周会",
    location: "五楼敏捷开发区",
    statusColor: "border-orange-500",
    attendees: [
      {
        name: "郑工",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/880ce581cc0c15ac6c23dead988216f1.jpg",
      },
      {
        name: "黄工",
        avatar:
          "https://ai-public.mastergo.com/ai/img_res/55e7fa552e8297c380b6ba6627c8cc8c.jpg",
      },
    ],
    totalAttendees: 12,
  },
]);

// 计算属性
const currentMonthYear = computed(() => {
  const year = currentMonth.value.getFullYear();
  const month = currentMonth.value.getMonth() + 1;
  return `${year}年${month}月`;
});

const calendarDays = computed(() => {
  const year = currentMonth.value.getFullYear();
  const month = currentMonth.value.getMonth();
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const days = [];

  // Previous month days
  const prevMonthDays = firstDay.getDay();
  const prevMonth = new Date(year, month, 0);
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    days.push({
      date: new Date(year, month - 1, prevMonth.getDate() - i).toISOString(),
      isCurrentMonth: false,
    });
  }

  // Current month days
  for (let i = 1; i <= lastDay.getDate(); i++) {
    days.push({
      date: new Date(year, month, i).toISOString(),
      isCurrentMonth: true,
    });
  }

  // Next month days
  const remainingDays = 42 - days.length;
  for (let i = 1; i <= remainingDays; i++) {
    days.push({
      date: new Date(year, month + 1, i).toISOString(),
      isCurrentMonth: false,
    });
  }

  return days;
});

// 方法
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}年${month}月${day}日`;
};

const prevMonth = () => {
  currentMonth.value = new Date(
    currentMonth.value.getFullYear(),
    currentMonth.value.getMonth() - 1
  );
};

const nextMonth = () => {
  currentMonth.value = new Date(
    currentMonth.value.getFullYear(),
    currentMonth.value.getMonth() + 1
  );
};

const selectDate = (date) => {
  selectedDate.value = new Date(date.date);
  showDatePicker.value = false;
};

const isSelectedDate = (date) => {
  const selected = new Date(selectedDate.value);
  const current = new Date(date.date);
  return (
    selected.getFullYear() === current.getFullYear() &&
    selected.getMonth() === current.getMonth() &&
    selected.getDate() === current.getDate()
  );
};

const handleClickOutside = (event) => {
  const calendar = document.querySelector(".calendar");
  if (
    calendar &&
    !calendar.contains(event.target) &&
    !event.target.closest("button")
  ) {
    showDatePicker.value = false;
  }
};

const loadMoreArticles = () => {
  if (loading.value || noMoreData.value) return;
  loading.value = true;
  setTimeout(() => {
    const start = (page.value - 1) * 3;
    const end = page.value * 3;
    const newArticles = allArticles.value.slice(start, end);
    if (newArticles.length > 0) {
      displayArticles.value = [...displayArticles.value, ...newArticles];
      page.value += 1;
    } else {
      noMoreData.value = true;
    }
    loading.value = false;
  }, 1000);
};

const handleScroll = (e) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target;
  if (scrollHeight - scrollTop - clientHeight <= 50) {
    loadMoreArticles();
  }
};

const initVisitChart = () => {
  const chart = echarts.init(visitChart.value);
  const option = {
    animation: false,
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "访问量",
        type: "line",
        smooth: true,
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        areaStyle: {
          opacity: 0.1,
        },
        itemStyle: {
          color: "#3B82F6",
        },
      },
    ],
  };
  chart.setOption(option);
};

const initUserChart = () => {
  const chart = echarts.init(userChart.value);
  const option = {
    animation: false,
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "用户分布",
        type: "pie",
        radius: "50%",
        data: [
          { value: 1048, name: "移动端" },
          { value: 735, name: "桌面端" },
          { value: 580, name: "平板" },
          { value: 484, name: "其他" },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  chart.setOption(option);
};

// 生命周期钩子
onMounted(() => {
  initVisitChart();
  initUserChart();
  loadMoreArticles();
  document.addEventListener("click", handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>
<style scoped>
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-10px);
  }

  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.calendar {
  animation: fadeIn 0.2s ease-out;
}

.dashboard-card {
  transition: all 0.3s ease;
}

.dashboard-card:hover {
  transform: translateY(-2px);
}

/* 行程状态颜色过渡动画 */
.border-l-4 {
  transition: all 0.3s ease;
}

/* 头像悬停效果 */
.rounded-full {
  transition: transform 0.2s ease;
}

.rounded-full:hover {
  transform: scale(1.2);
  z-index: 10;
}

input[type="checkbox"] {
  @apply w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500;
}

/* 自定义滚动条样式 */
.space-y-4::-webkit-scrollbar {
  width: 6px;
}

.space-y-4::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 6px;
}

.space-y-4::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 6px;
}

.space-y-4::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}
</style>
